//
//  DKWHomeViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/13.
//

#import "DKWHomeViewController.h"
#import "DKWHeaderTableViewCell.h"
#import "DKWCustomerServiceCell.h"
#import "DKWBannarTableViewCell.h"
#import "DKWOurAdvTableViewCell.h"
#import "DKWITeamUsersCell.h"
#import "XKWHomeTableViewCell.h"
#import "HomeRequest.h"
#import "XKWHeaderView.h"
#import "ImageLoader.h"
#import "LoadDetailsViewController.h"
#import "WebViewController.h"
#import "UUID.h"

@interface DKWHomeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,assign) BOOL isDKW;
@property (nonatomic ,strong) NSDictionary *dicInfo;
@property (nonatomic, strong) NSDictionary *dicDkwUserInfo;
@property (nonatomic, strong) NSArray *arrayDkwBannar;
@property (nonatomic, strong) NSArray *arrayXkwList;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) XKWHeaderView *xkwHeaderContentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutBgHeight;

@property (nonatomic , copy) NSString *faceng;

@end

@implementation DKWHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isDKW = YES;
    
  
  
    [self.tableView registerNib:[UINib nibWithNibName:@"DKWHeaderTableViewCell" bundle:nil] forCellReuseIdentifier:@"DKWHeaderTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DKWCustomerServiceCell" bundle:nil] forCellReuseIdentifier:@"DKWCustomerServiceCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DKWITeamUsersCell" bundle:nil] forCellReuseIdentifier:@"DKWITeamUsersCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DKWBannarTableViewCell" bundle:nil] forCellReuseIdentifier:@"DKWBannarTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DKWOurAdvTableViewCell" bundle:nil] forCellReuseIdentifier:@"DKWOurAdvTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"XKWHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"XKWHomeTableViewCell"];
    self.tableView.estimatedRowHeight = 44;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)_tableView.mj_header;
    [header setValue:@(YES) forKeyPath:@"stateLabel.hidden"];
    [header setValue:@(YES) forKeyPath:@"lastUpdatedTimeLabel.hidden"];
    
    self.xkwHeaderContentView =[[NSBundle mainBundle] loadNibNamed:@"XKWHeaderView" owner:self options:nil].firstObject;
    self.xkwHeaderContentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 260);
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 260)];
    [self.headerView addSubview:self.xkwHeaderContentView];
    self.xkwHeaderContentView.clipsToBounds = YES;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [HomeRequest requestUploadPagePointType:@"201" lightat:@""];
    [self headerRefresh];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [HomeRequest requestUploadPagePointType:@"202" lightat:@""];
    
}
- (void)headerRefresh{
    [self requestData];
    [self everyTimeUpdateHomeInfo];
}
- (void)requestData{
  
    __weak typeof(self) weakSelf = self;
    [HomeRequest requestHomeSuccess:^(NSURLSessionDataTask *task, id response) {
        [weakSelf.tableView.mj_header endRefreshing];
        if([response[@"ofexcitement"] integerValue] == 0){
            if(![response[@"pity"] isKindOfClass:[NSDictionary class]]){
                return;
            }
            weakSelf.faceng =  response[@"pity"][@"crept"][@"faceng"];
            NSArray *array = [NSArray arrayWithArray:response[@"pity"][@"tentacles"]];
            for (NSDictionary *dic in array) {
                if( [CHString(dic[@"spindly"]) isEqualToString:@"soundly"]){
                    weakSelf.arrayDkwBannar = [NSArray arrayWithArray:dic[@"humming"]];
                }else if ([CHString(dic[@"spindly"]) isEqualToString:@"slept"]){
                    weakSelf.isDKW = YES;
                    
                    weakSelf.layoutBgHeight.constant = 265;
                    if([dic[@"humming"] isKindOfClass:[NSArray class]]){
                        NSArray *array = [NSArray arrayWithArray:dic[@"humming"]];
                        if(array.count > 0){
                            weakSelf.dicInfo = array[0];
                        }
                    }else{
                        weakSelf.dicInfo = dic[@"humming"];
                    }
                    
                    [[ImageLoader sharedInstance] loadImageFromURL:[NSURL URLWithString:weakSelf.dicInfo[@"roundtinker"]] imageView:weakSelf.titleImageView completion:^(UIImage * _Nonnull image, NSError * _Nonnull error) {
                    }];
                    weakSelf.ch_title = CHString(weakSelf.dicInfo[@"noise"]);
                
                    weakSelf.tableView.tableHeaderView = [[UIView alloc] init];
                    
                }else if ([CHString(dic[@"spindly"]) isEqualToString:@"hadn"]){
                    weakSelf.isDKW = NO;
                    weakSelf.layoutBgHeight.constant = 265+200;
                    if([dic[@"humming"] isKindOfClass:[NSArray class]]){
                        NSArray *array = [NSArray arrayWithArray:dic[@"humming"]];
                        if(array.count > 0){
                            weakSelf.dicInfo = array[0];
                        }
                    }else{
                        weakSelf.dicInfo = dic[@"humming"];
                    }
                    weakSelf.ch_title = CHString(weakSelf.dicInfo[@"noise"]);
                    [[ImageLoader sharedInstance] loadImageFromURL:[NSURL URLWithString:weakSelf.dicInfo[@"roundtinker"]] imageView:weakSelf.titleImageView completion:^(UIImage * _Nonnull image, NSError * _Nonnull error) {
                    }];
                    
                    weakSelf.tableView.tableHeaderView = weakSelf.headerView;
                    [weakSelf.xkwHeaderContentView showDicInfo:weakSelf.dicInfo];
                    
                }else if ([CHString(dic[@"spindly"]) isEqualToString:@"ofexcitement"]){
                    weakSelf.arrayXkwList = [NSArray arrayWithArray:dic[@"humming"]];
                }else if ([CHString(dic[@"spindly"]) isEqualToString:@""]){
//                    weakSelf.dicDkwUserInfo = dic[@"humming"];
                }
            }
            
            [weakSelf.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.dicInfo.count == 0){
        return 0;
    }
    if(self.isDKW){
        return 5;
    }
    return self.arrayXkwList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if(!self.isDKW){
        XKWHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XKWHomeTableViewCell"];
        [cell showInfo:self.arrayXkwList[indexPath.row]];
        return cell;
    }
    
    if(indexPath.row == 1){
        DKWCustomerServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKWCustomerServiceCell"];
        cell.detailId = self.dicInfo[@"glad"];
        if( [UserInfoModel isLogin] ){
            cell.viewRate.color = UIColor.whiteColor;
            cell.viewRate.progress = self.faceng.floatValue/1000.0;
            cell.viewRate.hidden = NO;
            cell.imgViewCS.hidden = YES;
            cell.labelRateTitle.text = @"Credit rating";
            cell.labelNumber.text = CHString(self.faceng);
        }else{
            cell.viewRate.hidden = YES;
            cell.imgViewCS.hidden = NO;
            cell.labelRateTitle.text = @"Customer\nservice";
            cell.viewRate.progress = 0;
        }
        return cell;
    }else  if(indexPath.row == 2){
        DKWITeamUsersCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKWITeamUsersCell"];
        return cell;
    }else if(indexPath.row == 3){
        DKWBannarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKWBannarTableViewCell"];
        cell.arrayDkwBannar = self.arrayDkwBannar;
        return cell;
    }else if(indexPath.row == 4){
        DKWOurAdvTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKWOurAdvTableViewCell"];
       
        return cell;
    }
    DKWHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKWHeaderTableViewCell" forIndexPath:indexPath];
    [cell showDicInfo: self.dicInfo];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(!self.isDKW){
        return 140;
    }
    if(indexPath.row==1){
        return 170;
    }else if(indexPath.row==2){
        return 150;
    }else if(indexPath.row==3){
        return self.arrayDkwBannar.count == 0 ? 0: 135;
    }else if(indexPath.row==4){
        return UITableViewAutomaticDimension;
    }
    return 260;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(!self.isDKW){
        if( [UserInfoModel isLogin] ){
            __weak typeof(self) weakSelf = self;
            xhl_hudLoading();
            NSDictionary *dic = self.arrayXkwList[indexPath.row];
            [HomeRequest requestHomeCanpinLightat:dic[@"glad"] success:^(NSURLSessionDataTask *task, id response) {
                
                if( [response[@"ofexcitement"] integerValue] == 0 ){
                    xhl_hudDismiss();
                    NSString *spindly = CHString(response[@"pity"][@"spindly"]);
                    if(spindly.intValue == 1){
                        NSString *faint = CHString(response[@"pity"][@"faint"]);
                        if ([faint length] >= 4) {
                            NSString *substring = [faint substringToIndex:4];
                            if ([substring isEqualToString:@"http"]) {
                                WebViewController *webView = [[WebViewController alloc] init];
                                webView.url = [weakSelf getRequestUrlString:faint] ;
                                [[UIView xhl_getTopViewController].navigationController pushViewController:webView animated:YES];
                            } else {
                                
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:faint] options:@{} completionHandler:^(BOOL success) {
                                    
                                }];
                                
                            }
                        }
                        
                    }else{
                        LoadDetailsViewController *vc = [[LoadDetailsViewController alloc] init];
                        vc.detailId = dic[@"glad"];
                        [[UIView xhl_getTopViewController].navigationController pushViewController:vc animated:YES];
                    }
                }else{
                    xhl_showMessage(response[@"shared"]);
                }
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                xhl_showMessage(error.localizedDescription);
            }];
        }else{
            [UserInfoModel login];
        }
    }
}
- (NSString *)getRequestUrlString:(NSString *)str {
    
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSString *url= [NSString stringWithFormat:@"%@&areal=%@&boo=%@&howling=%@&ear=%@&knew=%@&minute=%@&which=1",str,[UserInfoModel getUserInfo].areal,appVersion,[BaseService friendlyDeviceName],[UUID getUUID],[[UIDevice currentDevice] systemVersion],[BaseService getIDFA]];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return url;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
